package cn.xsly.pet.service.impl;

import cn.xsly.pet.domain.PetType;
import cn.xsly.pet.mapper.PetTypeMapper;
import cn.xsly.pet.service.IPetTypeService;
import cn.xsly.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {
@Autowired
private PetTypeMapper petTypeMapper;
    @Override
    public List<PetType> petTypeTree() {
        List<PetType> types = petTypeMapper.findAll();
        Map<Long, PetType> map = new HashMap<>();
        for (PetType type : types) {
            map.put(type.getId(), type);
        }

        List<PetType> typeTree = new ArrayList<>();
        for (PetType type : types) {
            if (type.getParentId() == null) {//顶级类型
                typeTree.add(type);
            } else {//找父类型 - 将自己装到父类型的children中
                Long pid = type.getParentId();
                PetType parentType = map.get(pid);
                parentType.getChildren().add(type);
            }
        }
        return typeTree;

    }
}
